package com.example.demo.controller;

import com.example.demo.entity.Book;
import com.example.demo.mapper.BookMapper;
import com.example.demo.utils.PagingResult;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@CrossOrigin
@RestController
@RequestMapping("/book") // 控制器的前缀地址
public class BookController {
    @Autowired
    BookMapper bookMapper;

    /**
     * 获取分页的图书数据
     * @param limit 每页数量
     * @param offset 偏移量
     * @param field 搜索字段
     * @param code 搜索关键词
     * @return 分页结果
     */
    @GetMapping("/list")
    public PagingResult<Book> select(
            @RequestParam(required = false, name = "limit", defaultValue = "10") int limit,
            @RequestParam(required = false, name = "offset", defaultValue = "0") int offset,
            @RequestParam(required = false, name = "field") String field,
            @RequestParam(required = false, name = "code") String code
    ) {
        List<Book> bookList;
        int total;
        
        if (field != null && code != null && !code.trim().isEmpty()) {
            bookList = bookMapper.findByPageAndSearch(offset, limit, field, code);
            total = bookMapper.countBySearch(field, code);
        } else {
            bookList = bookMapper.findByPage(offset, limit);
            total = bookMapper.count();
        }
        
        return new PagingResult<Book>(bookList, total);
    }

    /**
     * 根据ID获取图书
     * @param id 图书ID
     * @return 图书对象
     */
    @GetMapping("/{id}")
    public Book getById(@PathVariable("id") int id) {
        return bookMapper.findById(id);
    }

    /**
     * 添加图书
     * @param book 图书对象
     * @return 影响行数
     */
    @PostMapping("/add")
    public int add(@RequestBody Book book) {
        return bookMapper.insert(book);
    }

    /**
     * 更新图书
     * @param book 图书对象
     * @return 影响行数
     */
    @PutMapping("/update")
    public int update(@RequestBody Book book) {
        return bookMapper.update(book);
    }

    /**
     * 删除图书
     * @param id 图书ID
     * @return 影响行数
     */
    @DeleteMapping("/delete/{id}")
    public int delete(@PathVariable("id") int id) {
        return bookMapper.delete(id);
    }
    
    /**
     * 获取所有图书
     * @return 图书列表
     */
    @GetMapping("/all")
    public List<Book> getAll() {
        return bookMapper.findAll();
    }
}